package com.lagou.rpc.consumer.config;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.client.RpcClientFactory;
import com.lagou.rpc.consumer.client.RpcClientForZk;
import com.lagou.rpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author liuc
 * @date 2021/6/3
 * @description
 **/
@Configuration
@EnableConfigurationProperties(RpcAddrProperties.class)
public class RpcConsumerConfig implements ApplicationContextAware {

    @Resource
    private RpcAddrProperties rpcAddrProperties;
    private ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Bean
    public IUserService userService() throws Exception {
        String host = context.getEnvironment().getProperty("zk.host");
        int port = Integer.parseInt(context.getEnvironment().getProperty("zk.port"));
        String path = context.getEnvironment().getProperty("zk.rpcPath");
        RpcClientFactory factory = new RpcClientFactory();
        //开启监听
        RpcClientForZk rpcClientForZk = new RpcClientForZk();
        rpcClientForZk.setFactory(factory);
        rpcClientForZk.configZk(host,port,path);
        RpcClientProxy rpcClientProxy = new RpcClientProxy();
        rpcClientProxy.setAddrs(rpcAddrProperties.getAddrs());
        rpcClientProxy.setRpcClientFactory(factory);
        //IUserService proxy = (IUserService) rpcClientProxy.createProxyForZk(IUserService.class);
        IUserService proxy = (IUserService) rpcClientProxy.createProxy(IUserService.class);
        return proxy;
    }
}
